from datetime import datetime
from django.shortcuts import render
from django.core.mail import send_mail
import random
import string
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
from django.http import HttpResponse,JsonResponse
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
import json
from casedemo9_smscode.models import CaseDemo9User
import uuid
from django.core.cache import cache
import jwt
from django.forms.models import model_to_dict
# 这种函数表示每个模块的测试地址，如果这个地址是正常的，说明路径是没问题的
SECRET_KEY = "djangobase+vue"
def index(request):
    context          = {}
    context['hello'] = 'Hello World! 这里是blogdemo8'
    print(cache.get('sms_code_12345678901'))
    return render(request, 'blogdemo8/index.html', context)
def generate_code(length=4):
    return ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
def get_random_color():
    return (random.randint(0, 150), random.randint(0, 150), random.randint(0, 150))
def image_code(request):
    code = generate_code()
    request.session['image_code'] = code
    width, height = 130, 50  # 可自定义尺寸
    image = Image.new('RGB', (width, height), (255, 255, 255))  # 背景白
    draw = ImageDraw.Draw(image)
    # 可自定义字体路径
    try:
        font = ImageFont.truetype("arial.ttf", 36)  # 更美观的字体（Windows系统）
    except:
        font = ImageFont.load_default()
    # 画验证码字符
    for i, char in enumerate(code):
        draw.text(
            (10 + i * 24, random.randint(0, 10)),  # 位置随机微调
            char,
            font=font,
            fill=get_random_color()
        )
    # 添加干扰线
    for _ in range(5):
        x1 = random.randint(0, width)
        y1 = random.randint(0, height)
        x2 = random.randint(0, width)
        y2 = random.randint(0, height)
        draw.line([(x1, y1), (x2, y2)], fill=get_random_color(), width=1)
    # 添加干扰点
    for _ in range(100):
        draw.point((random.randint(0, width), random.randint(0, height)), fill=get_random_color())
    buffer = BytesIO()
    image.save(buffer, 'png')
    # 将验证码存储到session中
    request.session['image_code'] = code.upper()
    return HttpResponse(buffer.getvalue(), content_type='image/png')

@csrf_exempt  # 前后端分离开发时需要禁用 CSRF（上线前应做好安全设置）
@require_POST
def send_sms_code(request):
    import json
    try:
        print(request.body)  # 打印原始数据
        print(request.headers)  # 查看 Content-Type 是否为 application/json
        data = json.loads(request.body)
        phone = data.get('phone')
        # 生成短信验证码
        sms_code = ''.join(random.choices('0123456789', k=6))
        cache_key_sms = f'sms_code_{phone}'
        cache.set(cache_key_sms, sms_code, timeout=300) # 存入缓存，有效期 5 分钟（300 秒）
        # 模拟发送短信（实际项目中要调用短信平台）
        print(f"【模拟短信】向 {phone} 发送验证码：{sms_code}")
        return JsonResponse({'code': 200, 'msg': '短信验证码已发送'})
    except Exception as e:
        print("出问题了")
        return JsonResponse({'code': 500, 'msg': f'服务异常: {str(e)}'}, status=500)
@csrf_exempt
@require_POST
def send_email_code(request):
    print(1111)
    data = json.loads(request.body)
    email = data.get('email')
    if not email:
        return JsonResponse({'code': 401, 'msg': '缺少邮箱地址'}, status=400)
    code = generate_code()
    print(22222)
    try:
        send_mail(
            subject='【验证码】你的登录验证码',
            message=f'你的验证码是：{code}，5分钟内有效。',
            from_email=None,  # 默认使用 settings.py 中的 DEFAULT_FROM_EMAIL
            recipient_list=[email],
            fail_silently=False,
        )
        # TODO: 将 code 存入缓存（如Redis）绑定 email，用于后续验证
        cache_key_emailcode = f'email_code_{email}'
        cache.set(cache_key_emailcode, code, timeout=300)  # 存入缓存，有效期 5 分钟（300 秒）
        # 模拟发送短信（实际项目中要调用短信平台）
        print(f"【模拟短信】向 {email} 发送验证码：{code}")
        return JsonResponse({'code': 200, 'msg': '邮箱验证码已发送'})
    except Exception as e:
        return JsonResponse({'code': 500, 'msg': f'服务异常: {str(e)}'}, status=500)

@csrf_exempt
@require_POST
def register_send_email_code(request):
    data = json.loads(request.body)
    email = data.get('email')
    if not email:
        return JsonResponse({'code': 401, 'msg': '缺少邮箱地址'}, status=400)
    code = generate_code()
    try:
        send_mail(
            subject='【验证码】你的注册验证码',
            message=f'你的验证码是：{code}，5分钟内有效。',
            from_email=None,  # 默认使用 settings.py 中的 DEFAULT_FROM_EMAIL
            recipient_list=[email],
            fail_silently=False,
        )
        # TODO: 将 code 存入缓存（如Redis）绑定 email，用于后续验证
        cache_key_emailcode = f'register_send_email_code_{email}'
        cache.set(cache_key_emailcode, code, timeout=300)  # 存入缓存，有效期 5 分钟（300 秒）
        # 模拟发送短信（实际项目中要调用短信平台）
        print(f"【模拟短信】向 {email} 发送验证码：{code}")
        return JsonResponse({'code': 200, 'msg': '邮箱验证码已发送'})
    except Exception as e:
        return JsonResponse({'code': 500, 'msg': f'服务异常: {str(e)}'}, status=500)

@csrf_exempt  # 前端跨域时必须加
def casedemo9login(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        loginmenthod=data.get('loginmenthod', None)
        if loginmenthod == 'phone':
            phone = data.get('phone', None)
            smscode = data.get('smscode', None)
            print(f"phone: {phone}, smscode: {smscode}")
            sms_code = cache.get(f'sms_code_{phone}')  # 从缓存中取出验证码
            if sms_code != data.get('smscode') or sms_code is None:
                return JsonResponse({'code': 403, 'msg': '短信验证码错误'})
            # 根据手机号查看用户
            user = CaseDemo9User.objects.get(phone=phone)
        elif loginmenthod == 'email':
            email = data.get('phone', None)
            emailcode = data.get('emilcode', None)
            print(f"email: {email}, emailcode: {emailcode}")
            email_code_fromcache = cache.get(f'email_code_{email}')  # 从缓存中取出验证码
            if email_code_fromcache != data.get('emilcode') or email_code_fromcache is None:
                return JsonResponse({'code': 403, 'msg': '邮箱验证码错误'})
            # 根据手机号查看用户
            user = CaseDemo9User.objects.get(email=email)
        elif loginmenthod == 'password':
            username = data.get('username', None)
            password = data.get('password', None)
            # 根据账户密码查看用户信息
            user = CaseDemo9User.objects.get(username=username, password=password)
        if user:# 登录成功才会保存缓存
            session_id = str(uuid.uuid4())  # 生成一个唯一 session 标识符
            request.session['session_id'] = session_id
            # ✅ 登录成功，将用户信息和权限存入缓存
            user_info = {
                'username': user.username,
                'sex': user.sex,
                'age': user.age,
                'phone': user.phone,
                'email': user.email,
                'session_id': session_id, # 将 session_id 存入用户信息
                'realname':user.realname,
                'card':user.card,
                'vxinfo':user.vxinfo,
                'address':user.address,
                'status':user.status,
                'role':user.role,
                'uuid':user.uuid,
                'descrption':user.descrption,
            }
            token = generate_jwt(username=user.username)# 创建token
            cache.set('token',token,timeout=60 * 60 * 2)
            cache.set(f'casedemo9_user_info_{user.useronlyID}',user_info,timeout=60 * 60 * 2)
            return JsonResponse({'code':888,'msg':'登录成功','userinfo':user_info,'token':token})
        else:
            return JsonResponse({'code': 403, 'msg': '用户名或密码错误'})
    return JsonResponse({'msg': '请求方法错误'}, status=405)
@csrf_exempt
@require_POST
def casedemo9_register(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        username = data.get('username', None)
        password = data.get('password', None)
        phone = data.get('phone', None)
        email = data.get('email', None)
        create_time= datetime.now()
        update_time= datetime.now()
        usernameuuid = uuid.uuid4()
        emailcode = data.get('emailcode', None)
        print(f"email: {email}, emailcode: {emailcode},1111111111111111111111111111111111")
        email_code_fromcache = cache.get(f'register_send_email_code_{email}')  # 从缓存中取出验证码
        print(f"缓存中的emailcode:{email_code_fromcache},data中的emailcode:{emailcode}")
        if email_code_fromcache != data.get('emailcode') or email_code_fromcache is None:
            return JsonResponse({'code': 403, 'msg': '邮箱验证码错误'})
        # 判断username,phone,email是否已经存在，这三个不可以重复
        if CaseDemo9User.objects.filter(username=username).exists():
            return JsonResponse({'code': 403, 'msg': '用户名已存在'})
        if CaseDemo9User.objects.filter(phone=phone).exists():
            return JsonResponse({'code': 403, 'msg': '手机号已存在'})
        if CaseDemo9User.objects.filter(email=email).exists():
            return JsonResponse({'code': 403, 'msg': '邮箱已存在'})
        # usernameuuid是唯一标识，如果是重复的那么就重新生成再加入
        while CaseDemo9User.objects.filter(useronlyID=usernameuuid).exists():
            usernameuuid = uuid.uuid4()
        try:
            # 保存用户信息
            user = CaseDemo9User.objects.create(
                username=username,
                password=password,
                phone=phone,
                email=email,
                uuid=usernameuuid,
                create_time=create_time,
                update_time=update_time
            )
            token=generate_jwt(username=username)
            cache.set('token', token, timeout=60 * 60 * 2)
            # 判断是否保存成功，成功就显示注册成功，否则显示失败
            if user:
                return JsonResponse({'code': 888, 'msg': '注册成功'})
            else:
                return JsonResponse({'code': 403, 'msg': '注册失败'})
        except Exception as e:
            return JsonResponse({'code': 403, 'msg': '注册失败'})
    else:
        return JsonResponse({'msg': '请求方法错误'}, status=405)

def verify_jwt(token):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
        return True,payload
    except jwt.ExpiredSignatureError:
        return False,[]
    except jwt.InvalidTokenError:
        return False,[]

from .models import Menu
import time
menu_data = [
    {
        "name": "工作台",
        "path": "/Index/Home",
        "icon": "Monitor",
        "create_date": int(time.time() * 1000),
        "description": "",
        "id": 1,
        "components": "HomePage",
        "requires_auth": True,
        "children": [],
        "permissions": ["edit", "delete"]
    },
    {
        "name": "业务菜单",
        "path": "/Index/Cutomer",
        "icon": "Position",
        "create_date": int(time.time() * 1000),
        "description": "",
        "id": 2,
        "requires_auth": True,
        "permissions": ["edit", "delete"],
        "children": [
            {
                "name": "列表示例",
                "path": "/Index/Cutomer/Table",
                "icon": "Grid",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 21,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "TableDemo"
            },
            {
                "name": "树形表格",
                "path": "/Index/Cutomer/TreeTable",
                "icon": "DataLine",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 22,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "TreeTableDemo"
            },
            {
                "name": "表单示例",
                "path": "/Index/Cutomer/Form",
                "icon": "Crop",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 23,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "FormDemo"
            },
            {
                "name": "详情示例",
                "path": "/Index/Cutomer/Info",
                "icon": "InfoFilled",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 23,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "ViewDemo"
            },
            {
                "name": "文件上传",
                "path": "/Index/Cutomer/File",
                "icon": "FolderOpened",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 24,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "UploadDemo"
            },
            {
                "name": "统计图表",
                "path": "/Index/Cutomer/Chart",
                "icon": "DataLine",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 24,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "ChartDemo"
            },
            {
                "name": "地图图表",
                "path": "/Index/Cutomer/MapChart",
                "icon": "Location",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 24,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "MapChartDemo"
            },
            {
                "name": "富文本示例",
                "path": "/Index/Cutomer/RichForm",
                "icon": "Discount",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 25,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "RichDemo"
            }
        ]
    },
    {
        "name": "基础数据",
        "path": "/Index/Data",
        "icon": "Connection",
        "create_date": int(time.time() * 1000),
        "description": "",
        "id": 3,
        "requires_auth": True,
        "permissions": ["edit", "delete"],
        "children": [
            {
                "name": "实体配置",
                "path": "/Index/Data/Entity",
                "icon": "Reading",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 32,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "EntityConfig"
            },
            {
                "name": "消息数据",
                "path": "/Index/Data/Message",
                "icon": "ChatLineSquare",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 31,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "Message"
            },
            {
                "name": "已读记录",
                "path": "/Index/Data/MessageRead",
                "icon": "View",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 31,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "MessageRead"
            },
            {
                "name": "验证码数据",
                "path": "/Index/Data/Code",
                "icon": "Picture",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 33,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "Code"
            }
        ]
    },
    {
        "name": "系统管理",
        "path": "/Index/System",
        "icon": "Setting",
        "create_date": int(time.time() * 1000),
        "description": "",
        "id": 4,
        "requires_auth": True,
        "permissions": ["edit", "delete"],
        "children": [
            {
                "name": "用户管理",
                "path": "/Index/System/user",
                "icon": "UserFilled",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 41,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "User"
            },
            {
                "name": "角色管理",
                "path": "/Index/System/Role",
                "icon": "Avatar",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 42,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "Role"
            },
            {
                "name": "权限管理",
                "path": "/Index/System/Permission",
                "icon": "Lock",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 43,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "Permission"
            },
            {
                "name": "菜单管理",
                "path": "/Index/System/Menu",
                "icon": "Menu",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 44,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "Menu"
            },
            {
                "name": "数据字典",
                "path": "/Index/System/Dict",
                "icon": "Notebook",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 45,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "Dict"
            },
            {
                "name": "缓存管理",
                "path": "/Index/Data/Cache",
                "icon": "Files",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 32,
                "requires_auth": True,
                "permissions": ["delete"],
                "components": "Cache"
            },
            {
                "name": "日志管理",
                "path": "/Index/System/Log",
                "icon": "Grid",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 45,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "Log"
            },
            {
                "name": "系统配置",
                "path": "/Index/System/Setting",
                "icon": "Setting",
                "create_date": int(time.time() * 1000),
                "description": "",
                "id": 46,
                "requires_auth": True,
                "permissions": ["edit", "delete"],
                "components": "Setting"
            }
        ]
    }
]

def timestamp_to_datetime(ms_timestamp):
    """将毫秒时间戳转换为 datetime 对象"""
    return datetime.fromtimestamp(ms_timestamp / 1000)
from django.http import JsonResponse

def init_menu_data(request):
    def create_menu(data, parent=None):
        # 创建菜单实例（写入数据库）
        menu = Menu.objects.create(
            name=data['name'],
            path=data['path'],
            icon=data.get('icon', ''),
            requires_auth=data.get('requires_auth', True),
            description=data.get('description', ''),
            components=data.get('components', ''),
            permissions=data.get('permissions', []),
            create_date=datetime.fromtimestamp(data['create_date'] / 1000),
            parent=parent
        )
        # 如果有子菜单，递归创建
        for child in data.get('children', []):
            create_menu(child, parent=menu)
    # 执行插入
    for item in menu_data:
        create_menu(item)
    return JsonResponse({"status": "ok", "message": "菜单数据初始化完成"})

# 获得菜单的初始化数据
@csrf_exempt
def get_menu_data(request):
    """
    查询菜单数据，并组织成树形结构返回
    """
    def build_menu_tree(menu_queryset):
        """
        递归构建菜单树
        """
        tree = []
        for menu in menu_queryset:
            item = {
                "id": menu.id,
                "name": menu.name,
                "path": menu.path,
                "icon": menu.icon,
                "requires_auth": menu.requires_auth,
                "create_date": int(menu.create_date.timestamp() * 1000),  # 转为前端常用的毫秒时间戳
                "description": menu.description,
                "components": menu.components,
                "permissions": menu.permissions,
                "children": build_menu_tree(menu.children.all())  # 递归处理子菜单
            }
            tree.append(item)
        return tree
    # 查询所有顶级菜单（parent为空）
    root_menus = Menu.objects.filter(parent__isnull=True).order_by('id')
    # 组织成树形
    menu_tree = build_menu_tree(root_menus)
    return JsonResponse({"code": 888, "msg": "success", "data": menu_tree})

from datetime import datetime, timedelta
def generate_jwt(username):
    payload = {
        "username": username,
        "exp": datetime.utcnow() + timedelta(hours=1)  # 有效期1小时
    }
    # 直接返回字符串类型的 token
    token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
    return token  # 不需要 decode